/* ====================================================================
   Copyright (C) 2011 Krzysztof Marecki

   This file is part of the NReports project.
	
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


   For additional information, email dotnetreports@gmail.com
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

using NReports.RDL;

namespace NReports.RdlAsp
{
    public class RenderHtmlPages
    {
        StringWriter sw;
		CultureInfo cinf;
		IStreamGen sg;
		
		public RenderHtmlPages (IStreamGen streamgen)
		{
			sg = streamgen;
		}

        public void RunPages(Pages pages)
        {
			//avoid drawing duplicated borders
			ReduceBorders (pages);
            sw = new StringWriter ();
			cinf = CultureInfo.GetCultureInfo("en-us");
			
			sw.WriteLine ("<tr><td><table style=\"position: relative;\">");
			sw.WriteLine ("<div style=\"position: relative;height: {0}pt;width: {1}pt\">", 
				ToHtmlString(pages.PageHeight),
				ToHtmlString(pages.PageWidth));
            foreach (PageItem pi in pages[0]) {
				if (pi is PageText) {
					DrawText ((PageText)pi);
				}
				if (pi is PageRectangle) {
					DrawRectangle ((PageRectangle)pi);
				}
				if (pi is PageImage) {
					DrawImage ((PageImage)pi);
				}
				if (pi is PageLine) {
					DrawLine ((PageLine)pi);
				}
            }
			sw.WriteLine ("</div>");
			sw.WriteLine("</table></td></tr>");
			
            Html = sw.GetStringBuilder().ToString();
        }

        public string Html { get; private set; }
		
		private void ReduceBorders (Pages pages)
		{
			Page page = pages [0];
			var items = from it in page.Cast<PageItem> ()
						select it;
			
			var rights = from p in items
							join p2 in items on (p.X + p.W) equals p2.X
							where p.Y == p2.Y
						 	select new { First = p, Second = p2 };
			
			foreach (var right in rights) {
				if (right.Second.SI.BStyleLeft != BorderStyleEnum.None) {
					right.First.SI.BStyleRight = BorderStyleEnum.None;
				}
			}
			
			var bottoms = from p in items
							join p2 in items on (p.Y + p.H) equals p2.Y
							where p.X == p2.X
						 	select new { First = p, Second = p2 };
			
			foreach (var bottom in bottoms) {
				if (bottom.Second.SI.BStyleTop != BorderStyleEnum.None) {
					bottom.First.SI.BStyleBottom = BorderStyleEnum.None;
				}
			}
		}
		
		private string ToHtmlString (float f)
		{
			return Convert.ToString (Math.Round (f), cinf);
		}
		
		private string ToCssColor (System.Drawing.Color cl)
		{
			string color = cl.ToKnownColor ().ToString ();
			if (color != "0") 
				return color;
			
			
			return (cl.R != 0 || cl.G != 0 || cl.B != 0) ? 
				string.Format("#{0:X}{1:X}{2:X}", cl.R, cl.G, cl.B) :
				"transparent";
		}
		
		private string ToCssFontWeight (FontWeightEnum wgh)
		{
			string weight = wgh.ToString ().ToLower ();
			return (weight.IndexOf ("w") != 0) ? weight : weight.Remove (0, 1);
		}
		
		private string GetCssStyle (PageItem pi)
		{
			StringBuilder style = new StringBuilder ();
			style.Append ("position: absolute;");
			float width = pi.W;
			style.AppendFormat ("width: {0}pt;", ToHtmlString (width));
			float height = pi.H;
			style.AppendFormat ("height: {0}pt;", ToHtmlString (height));
			float left = pi.X;
			style.AppendFormat ("left: {0}pt;", ToHtmlString (left));
			float top = pi.Y;
			style.AppendFormat ("top: {0}pt;", ToHtmlString (top));
			style.AppendFormat ("border-left: {0} {1} {2}pt;", 
				pi.SI.BStyleLeft, 
				ToCssColor (pi.SI.BColorLeft),
				ToHtmlString (pi.SI.BWidthLeft));
			style.AppendFormat ("border-top: {0} {1} {2}pt;", 
				pi.SI.BStyleTop, 
				ToCssColor (pi.SI.BColorTop),
				ToHtmlString (pi.SI.BWidthTop));
			style.AppendFormat ("border-right: {0} {1} {2}pt;", 
				pi.SI.BStyleRight, 
				ToCssColor (pi.SI.BColorRight),
				ToHtmlString (pi.SI.BWidthRight));
			style.AppendFormat ("border-bottom: {0} {1} {2}pt;", 
				pi.SI.BStyleBottom, 
				ToCssColor (pi.SI.BColorBottom),
				ToHtmlString (pi.SI.BWidthBottom));
			
			style.AppendFormat ("background-color: {0};", ToCssColor (pi.SI.BackgroundColor));
			style.AppendFormat ("color : {0};", ToCssColor (pi.SI.Color));
			return style.ToString ();
		}
		
		public string GetCssStyleText (PageText pi)
		{
			StringBuilder style = new StringBuilder ();
			style.Append ("position: absolute;");
			float width = pi.W - pi.SI.PaddingLeft - pi.SI.PaddingRight;
			style.AppendFormat ("width: {0}pt;", ToHtmlString (width));
			float height = pi.H - pi.SI.PaddingTop - pi.SI.PaddingBottom;
			style.AppendFormat ("height: {0}pt;", ToHtmlString (height));
			float left = pi.SI.PaddingLeft;
			style.AppendFormat ("left: {0}pt;", ToHtmlString (left));
			float top = pi.SI.PaddingTop;
			style.AppendFormat ("top: {0}pt;", ToHtmlString (top));
			//style.AppendFormat ("background-color: {0};", ToCssColor (pi.SI.BackgroundColor));
			style.AppendFormat ("color : {0};", ToCssColor (pi.SI.Color));
			style.AppendFormat ("text-align: {0};", pi.SI.TextAlign);
			style.AppendFormat ("vertical-align: {0};", pi.SI.VerticalAlign);
			style.AppendFormat ("font-style: {0};", pi.SI.FontStyle);
			style.AppendFormat ("font-family: {0};", pi.SI.FontFamily);
			style.AppendFormat ("font-weight: {0};", ToCssFontWeight(pi.SI.FontWeight));
			style.AppendFormat ("font-size: {0}pt;", ToHtmlString (pi.SI.FontSize));
		
			return style.ToString ();
		}
		
		public string GetCssStyleLine (PageLine pi)
		{
			StringBuilder style = new StringBuilder ();
			style.Append ("position: absolute;");
			float width = pi.X2 - pi.X;
			style.AppendFormat ("width: {0}pt;", ToHtmlString (width));
			style.AppendFormat ("height: {0}pt;", ToHtmlString (pi.SI.BWidthTop));
			float left = pi.X;
			style.AppendFormat ("left: {0}pt;", ToHtmlString (left));
			float top = pi.Y;
			style.AppendFormat ("top: {0}pt;", ToHtmlString (top));
			style.AppendFormat ("border-top: {0} {1} {2}pt;", 
				pi.SI.BStyleTop, 
				ToCssColor (pi.SI.BColorTop),
				ToHtmlString (pi.SI.BWidthTop));
		
			return style.ToString ();
		}
		
		private void DrawText (PageText pi)
		{
			sw.WriteLine("<div style=\"{0}\"><div style=\"{1}\">{2}</div></div>",
				GetCssStyle (pi),
				GetCssStyleText (pi), pi.Text);
		}
		
		private void DrawRectangle (PageRectangle pi)
		{
			sw.WriteLine("<div style=\"{0}\"></div>", GetCssStyle (pi));
		}
		
		private void DrawImage (PageImage pi)
		{
			string suffix;
			string relativeName;
			
			if (pi.ImgFormat.Guid == ImageFormat.Bmp.Guid) {
				suffix = "bmp";
			}
			else if (pi.ImgFormat.Guid == ImageFormat.Jpeg.Guid) {
				suffix = "jpeg";
			}
			else if (pi.ImgFormat.Guid == ImageFormat.Gif.Guid) {
				suffix = "gif";
			}
			else if (pi.ImgFormat.Guid == ImageFormat.Png.Guid) {
				suffix = "png";
			}
			else {
				suffix = "unk";
			}
			
			Stream ioin = new MemoryStream (pi.ImageData);
			Stream io = sg.GetIOStream(out relativeName, suffix);
			try
			{   
				if (ioin.CanSeek)		// ioin.Length requires Seek support
				{
					byte[] ba = new byte[ioin.Length];
					ioin.Read(ba, 0, ba.Length);
					io.Write(ba, 0, ba.Length);
				}
				else
				{
					byte[] ba = new byte[1000];		// read a 1000 bytes at a time
					while (true)
					{
						int length = ioin.Read(ba, 0, ba.Length);
						if (length <= 0)
							break;
						io.Write(ba, 0, length);
					}
				}
			}
			finally
			{
				io.Flush();
				io.Close();
			}
			
			sw.WriteLine("<div style=\"{0}\"><img src=\"{1}\" /></div>",
			             GetCssStyle(pi), relativeName);
		}
		
		private void DrawLine (PageLine pi)
		{
			sw.WriteLine("<hr style=\"{0}\"/>", GetCssStyleLine (pi));
		}
    }
}
